package com.xjtucrafter.kiwi.merchant.service.impl;

import com.xjtucrafter.kiwi.merchant.bean.Merchant;
import com.xjtucrafter.kiwi.merchant.dao.MerchantDao;
import com.xjtucrafter.kiwi.merchant.service.MerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.NoResultException;
import java.util.List;

/**
 * User: Dash
 * Date: 4/21/16 Time: 1:24 PM
 */
@Service("merchantService")
public class MerchantServiceImpl implements MerchantService{

    @Autowired
    private MerchantDao merchantDao;

    @Override
    @Transactional
    public boolean merchantAdd(Merchant merchant) {
        int result = merchantDao.merchantAdd(merchant);
        return result >= 0;
    }

    @Override
    public Merchant merchantQuery(String merchantName) {
        try{
            return merchantDao.merchantQuery(merchantName);
        }catch (NoResultException e){
            return null;
        }
    }

    @Override
    public List<Merchant> merchantBatchQuery() {
        try {
            return merchantDao.merchantBatchQuery();
        }catch (NoResultException e){
            return null;
        }
    }

    @Override
    @Transactional
    public boolean merchantUpdate(Merchant merchant) {
        int result = 0;
        if(merchant.isMerchantIsAccepted()){
            result = merchantDao.merchantUpdate(merchant, true);
        }else{
            result = merchantDao.merchantUpdate(merchant);
        }
        return result > 0;
    }

    @Override
    @Transactional
    public boolean merchantDelete(String merchantName) {
        int result = merchantDao.merchantDelete(merchantName);
        return result > 0;
    }

    @Override
    public boolean merchantQuery(String name, String password) {
        Merchant merchant = merchantDao.merchantQuery(name);
        return merchant != null && password.equals(merchant.getMerchantPassword());
    }
}
